package com.ruoyi.web.controller;

import com.ruoyi.sunshine.domain.TestPicData;
import com.ruoyi.sunshine.file.FileService;
import com.ruoyi.sunshine.mapper.UploadImageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@CrossOrigin("*")
public class UploadImageController {

    @Autowired
    private FileService fileService;

    @Autowired
    private UploadImageMapper uploadImageMapper;

    @RequestMapping(value = "/pic/test", method = RequestMethod.GET)
    public String upload2(String id) {
        return "id==" + id;
    }

    @RequestMapping(value = "/pic/upload", method = RequestMethod.POST)
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        TestPicData testPic = new TestPicData();
        byte[] contents = fileService.getByteByInputStream(file.getInputStream(), null);
        testPic.setPicData(contents);
        testPic.setPicName(file.getOriginalFilename());
        Long i = uploadImageMapper.insertPicture(testPic);
        System.out.println("===============================");
        System.out.println("id==" + i);
        return "id==" + i;
    }

    @ResponseBody
    @RequestMapping(value = "/pic/get", method = RequestMethod.GET)
    public ResponseEntity<Object> upload(String id) throws IOException {
        Long picId = Long.valueOf(id);
        TestPicData testPicData = uploadImageMapper.getListById(picId);
        byte[] picData1 = testPicData.getPicData();

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE,"image/png");
        return new ResponseEntity<Object>(picData1,headers, HttpStatus.OK);
    }

    @DeleteMapping("/testDelete")
    public String testDelete(@RequestBody @Validated Map map){
        if(map == null){
            return "失败";
        }
        return "成功";
    }
}
